//
//  XJ_ForgetPasswordViewController.m
//  XunJieProject
//
//  Created by 薛子 on 2018/6/7.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_ForgetPasswordViewController.h"
#import "TregularexpressionNSObjec.h"
@interface XJ_ForgetPasswordViewController ()

@property (weak, nonatomic) IBOutlet UIView *phoneView;

@property (weak, nonatomic) IBOutlet UIView *codeView;

@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxt;

@property (weak, nonatomic) IBOutlet UITextField *codeTxt;

@property (weak, nonatomic) IBOutlet UITextField *passwordTxt;

@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIButton *changePasswordBtn;
@property (weak, nonatomic) IBOutlet UIView *picView;

@property (weak, nonatomic) IBOutlet UITextField *picTxt;

@property (weak, nonatomic) IBOutlet UIImageView *picImage;



@end

@implementation XJ_ForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nav_btmView.backgroundColor = [UIColor clearColor];
    self.nav_titleLabel.text = @"重置密码";
    [self.nav_backButton setImage:[UIImage imageNamed:@"close_btn"] forState:UIControlStateNormal];
//    self.nav_backButton.frame = CGRectMake(20,30, 20, 20);
    
    [self getPictureCode];
    
    _phoneView.layer.cornerRadius = 4;
    _phoneView.layer.borderWidth = 1.5;
    _phoneView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _phoneTxt.keyboardType = UIKeyboardTypeNumberPad;
     [_phoneTxt addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    _picView.layer.cornerRadius = 4;
    _picView.layer.borderWidth = 1.5;
    _picView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _picTxt.keyboardType = UIKeyboardTypeNumberPad;
    
    _codeView.layer.cornerRadius = 4;
    _codeView.layer.borderWidth = 1.5;
    _codeView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _codeTxt.keyboardType = UIKeyboardTypeNumberPad;
    
    _passwordView.layer.cornerRadius = 4;
    _passwordView.layer.borderWidth = 1.5;
    _passwordView.layer.borderColor  = [UIColor whiteColor].CGColor;
    
    _codeButton.layer.cornerRadius = 4;
    _changePasswordBtn.layer.cornerRadius = 4;
    
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"手机号码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_phoneTxt.font
                                        }];
    _phoneTxt.attributedPlaceholder = attrString;
    
    NSAttributedString *attrString2 = [[NSAttributedString alloc] initWithString:@"验证码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_codeTxt.font
                                        }];
    _codeTxt.attributedPlaceholder = attrString2;
    
    NSAttributedString *attrString3 = [[NSAttributedString alloc] initWithString:@"重新设置密码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_passwordTxt.font
                                        }];
    _passwordTxt.attributedPlaceholder = attrString3;
    
    NSAttributedString *attrString4 = [[NSAttributedString alloc] initWithString:@"图片验证码" attributes:
                                       @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                         NSFontAttributeName:_picTxt.font
                                         }];
    _picTxt.attributedPlaceholder = attrString4;
    
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)getVerifyCode:(id)sender{
    
    if (_phoneTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    if (![TregularexpressionNSObjec isMobileNumber:_phoneTxt.text]) {
        
        [XJ_Utils alertViewWithMessage:@"请输入正确手机号"];
        return;
    }
    
    if (_picTxt.text.length == 0) {

        [XJ_Utils alertViewWithMessage:@"请输入图片验证码"];
        return;
    }
    
    NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSLog(@"设备唯一标识符:%@",identifierStr);
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:identifierStr forKey:@"equipmentNo"];
    [dic setValue:@(2)forKey:@"verifyCodeType"];
    [dic setValue:_phoneTxt.text forKey:@"mobile"];
    [dic setValue:_picTxt.text forKey:@"identifyCode"];
    
    [XJ_Utils post:@"user/beforeSendVerify?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        [XJ_Utils alertViewWithMessage:@"验证码发送成功"];
        [self startAnimation];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [XJ_Utils alertViewWithMessage:@"验证码发送失败"];
        
    }];
    
}
- (IBAction)changePasswordAction:(id)sender {
    
    if (_phoneTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    if (![TregularexpressionNSObjec isMobileNumber:_phoneTxt.text]) {
        
        [XJ_Utils alertViewWithMessage:@"请输入正确手机号"];
        return;
    }
    
    if (_codeTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入验证码"];
        return;
    }
    
    if (_passwordTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入密码"];
        return;
    }
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
//    [dic setValue:[[_passwordTxt.text md5HexDigest] uppercaseString]forKey:@"newPassword"];
    [dic setValue:_passwordTxt.text forKey:@"newPassword"];
    [dic setValue:_phoneTxt.text forKey:@"mobile"];
    [dic setValue:_codeTxt.text forKey:@"verifyCode"];

    [XJ_Utils post:@"user/resetPassword?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"修改成功，请登录" image:@"pop_msg_succeed_xs"];
        [alext showXLAlertView];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}


- (IBAction)getPicImage:(id)sender {
    
    [self getPictureCode];
}
//获取图片验证码
- (void)getPictureCode{
    
    NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSLog(@"设备唯一标识符:%@",identifierStr);
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:identifierStr forKey:@"equipmentNo"];
    [dic setValue:@(1)forKey:@"verifyCodeType"];
    
    NSString * urlStr = [NSString stringWithFormat:@"%@user/getPicCode?equipmentNo=%@&verifyCodeType=2",HOSTURL,identifierStr];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [[SDImageCache sharedImageCache] clearMemory];
//    [_picImage sd_setImageWithURL:[NSURL URLWithString:urlStr]];
    [_picImage sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"img_no_image"] options:SDWebImageAllowInvalidSSLCertificates];
}
- (void)startAnimation
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self->_codeButton setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                [self->_codeButton setBackgroundColor:[UIColor orangeColor]];
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self->_codeButton setTitle:[NSString stringWithFormat:@"剩余%d秒",seconds] forState:UIControlStateNormal];
                [self->_codeButton setBackgroundColor:[UIColor lightGrayColor]];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
}
- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == self.phoneTxt) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
